package com.ruoyi.core.config.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.domain.ChatRequestBo;
import com.ruoyi.gpt.domain.vo.WxMsgVo;
import com.ruoyi.gpt.listener.OpenAIWebSocketEventSourceListener;
import com.ruoyi.gpt.service.IWxMsgService;
import com.unfbx.chatgpt.OpenAiStreamClient;
import com.unfbx.chatgpt.entity.chat.ChatCompletion;
import com.unfbx.chatgpt.entity.chat.Message;
import com.unfbx.chatgpt.interceptor.OpenAILogger;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import org.apache.commons.lang3.StringUtils;

import javax.websocket.Session;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

@Slf4j
@RequiredArgsConstructor
public class OpenAiUtil {
    private final  IWxMsgService wxMsgService;
    // 发起请求
    public static void sendRequest(ChatRequestBo chatRequestBo,String apiHost, String apiKey,List<WxMsgVo> oldMsgList) {
        //国内访问需要做代理，国外服务器不需要
        //Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 7890));
        //HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new OpenAILogger());
        //httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient okHttpClient = new OkHttpClient
            .Builder()
            // .proxy(proxy) //  拦截器
            // .addInterceptor(httpLoggingInterceptor) // 拦截器
            .connectTimeout(60, TimeUnit.SECONDS)
            .writeTimeout(60, TimeUnit.SECONDS)
            .readTimeout(60, TimeUnit.SECONDS)
            .build();

        OpenAiStreamClient openAiStreamClient = OpenAiStreamClient
            .builder()
            .okHttpClient(okHttpClient)
            .apiHost(apiHost)
            .apiKey(Arrays.asList(apiKey))
            .build();
        //接受参数
        OpenAIWebSocketEventSourceListener eventSourceListener = new OpenAIWebSocketEventSourceListener(chatRequestBo);
        String messageContext ="";
        List<Message> messages = new ArrayList<>();
        StringBuilder totalMsgLength = new StringBuilder();
        for (WxMsgVo wxMsgVo : oldMsgList) {
            String question = wxMsgVo.getDetail(); // 提问的问题
            String repContent = wxMsgVo.getRepContent(); // 获得的回复
            if(StringUtils.isNotBlank(question) && StringUtils.isNotBlank(repContent)&& totalMsgLength.length()<2000){
                totalMsgLength.append(question).append(repContent);
                Message userMessage = Message.builder().role(Message.Role.USER).content(question).build();
                Message assistantMessage = Message.builder().role(Message.Role.ASSISTANT).content(repContent).build();
                messages.add(0,userMessage);
                messages.add(1,assistantMessage);
            }
        }

        if (StrUtil.isNotBlank(messageContext)) {
            messages = JSONUtil.toList(messageContext, Message.class);
            if (messages.size() >= 10) {
                messages = messages.subList(1, 10);
            }
            Message currentMessage = Message.builder().content(chatRequestBo.getQuestion()).role(Message.Role.USER).build();
            messages.add(currentMessage);
        } else {
            Message currentMessage = Message.builder().content(chatRequestBo.getQuestion()).role(Message.Role.USER).build();
            messages.add(currentMessage);
        }
        ChatCompletion chatCompletionV2 = ChatCompletion
            .builder()
            .messages(messages)
            .model(ChatCompletion.Model.GPT_3_5_TURBO_16K_0613.getName())
            .build();
        openAiStreamClient.streamChatCompletion(chatCompletionV2, eventSourceListener);
    }
}
